<script setup lang="ts">
import {
  exportCompleteDetail,
  exportCompleteList,
  exportFinanceDetail,
  exportFinanceList,
  exportMonthPlan,
  exportYearPlan,
} from '@/api/project-update/download-api'
import { getCurrentInstance } from 'vue'
import { Message } from 'element-ui'

const vm = getCurrentInstance()

const currentUser = vm.proxy.$store.state.user.currentUser

const props = defineProps({
  type: String,
  params: [Object, Array],
  disabled: Boolean,
  permission: String,
  dataCheck: Function,
})

function fileDownload(file, fileName = '下载文件', options) {
  // 创建隐藏的可下载链接
  let eleLink = document.createElement('a')
  eleLink.download = fileName
  eleLink.style.display = 'none'
  // 字符内容转变成blob地址
  let blob = options ? new Blob([file], options) : new Blob([file])
  eleLink.href = URL.createObjectURL(blob)
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

const handleDownloadClick = async () => {
  let promise
  try {
    props.dataCheck && (await props.dataCheck())
    switch (props.type) {
      case 'month-plan':
        promise = exportMonthPlan(props.params)
        break
      case 'year-plan':
        promise = exportYearPlan(props.params)
        break
      case 'complete-detail':
        promise = exportCompleteDetail(props.params)
        break
      case 'complete-list':
        promise = exportCompleteList(props.params)
        break
      case 'finance-detail':
        promise = exportFinanceDetail(props.params)
        break
      case 'finance-list':
        promise = exportFinanceList(props.params)
        break
      default:
        promise = Promise.resolve()
        break
    }
    promise
      .then((res) => {
        if (!res.data) return
        fileDownload(res.data, '表格数据.xlsx')
      })
      .catch((res) => {
        console.log(res)
      })
  } catch (e) {
    //
  }
}
</script>

<template>
  <el-button
    v-if="permission ? currentUser?.hasPermission(permission) : true"
    class="common-download"
    @click="handleDownloadClick"
    :disabled="disabled"
    icon="el-icon-download"
    type="primary"
  >
    {{ permission ? currentUser?.getButtonName(permission) : '下载' }}
  </el-button>
</template>

<style scoped lang="scss">
.common-download {
  margin-right: 12px;
}
</style>
